const express = require('express');
const Axios = require('axios');
const router = express.Router();
const db = require('../db/mysql');
const CryptoJS = require('crypto-js');

var checkToken = (req,res,next)=>{
  // 解密
  try{
    const secretKey = process.env.API_SECRET_KEY // 密钥，需要和前端保持一致
    const ciphertext = req.body.data // 接收到的加密参数
    const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
      mode: CryptoJS.mode.ECB, // 模式
      padding: CryptoJS.pad.Pkcs7 // 填充
    }).toString(CryptoJS.enc.Utf8); // 明文
    const plaintext = decrypted
    const data = JSON.parse(plaintext)
    const timestamp = Date.now()
    if(Math.abs(data.timestamp - timestamp) > 10000){
        res.status(400).send('请求超时');
    }else{
        req.data = data
        next()
    }
  }catch(e){
    res.status(500).send('请求异常');
  }
}

/* GET home page. */
router.post('/addPrompt', checkToken, async function(req, res){
  try{
    let prompt = req.data.prompt
    let userId = req.data.userId
    if(!userId || !prompt){
      res.json({msg: '参数错误'})
      return
    }
    let config = sendConfigFirst(prompt)
    let res_send = await sendToDiscord(config)

    if(res_send){
      let create_at = datetime()
      let sql = 'insert into user_prompt_url set status = 1, type = 1, user_id = "'+ userId +'", prompt = "'+ prompt +'", create_at = "'+ create_at +'"'
      let response  = await db.query(sql)
      if(response){
        res.json({code: 1, msg: '成功'})
      }else{
        res.json({code: 0, msg: '失败'})
      }
    }else{
        res.json({code: 0, msg: '发送失败'})
    }
  }catch(error){
    console.log(error)
    res.json({error})
  }
})

router.post('/chooseDetail', checkToken, async function(req, res){
  try{
    let prompt = req.data.prompt
    let userId = req.data.userId
    let messageId = req.data.messageId
    let num = req.data.num
    let messageName = req.data.messageName
    if(!userId || !prompt || !num || !messageName || !messageId){
      res.json({msg: '参数错误'})
      return
    }
    let config = sendConfigDetail(messageId, num, messageName)
    let res_send = await sendToDiscord(config)

    if(res_send){
      let create_at = datetime()
      let sql = 'insert into user_prompt_url set status = 1, type = 2, user_id = "'+ userId +'", prompt = "'+ prompt +'", create_at = "'+ create_at +'"'
      let response  = await db.query(sql)
      if(response){
        res.json({code: 1, msg: '成功'})
      }else{
        res.json({code: 0, msg: '失败'})
      }
    }else{
        res.json({code: 0, msg: '发送失败'})
    }
  }catch(error){
    console.log(error)
    res.json({error})
  }
})

router.post('/chooseNew', checkToken, async function(req, res){
  try{
    let prompt = req.data.prompt
    let userId = req.data.userId
    let messageId = req.data.messageId
    let num = req.data.num
    let messageName = req.data.messageName
    if(!userId || !prompt || !num || !messageName || !messageId){
      res.json({msg: '参数错误'})
      return
    }
    let config = sendConfigNew(messageId, num, messageName)
    let res_send = await sendToDiscord(config)

    if(res_send){
      let create_at = datetime()
      let sql = 'insert into user_prompt_url set status = 1, type = 1, user_id = "'+ userId +'", prompt = "'+ prompt +'", create_at = "'+ create_at +'"'
      let response  = await db.query(sql)
      if(response){
        res.json({code: 1, msg: '成功'})
      }else{
        res.json({code: 0, msg: '失败'})
      }
    }else{
        res.json({code: 0, msg: '发送失败'})
    }
  }catch(error){
    console.log(error)
    res.json({error})
  }
})

router.post('/getList', checkToken, async function(req, res){
  try{
    let userId = req.data.userId
    if(!userId){
      res.json({msg: '参数错误'})
      return
    }
    let sql = 'select * from user_prompt_url where status = 2 and user_id = "'+ userId + '" order by id desc'
    let response = await db.query(sql)
    if(response){
        res.json({'data': response})
    }else{
        res.json({msg: '查询失败'})
    }
  }catch(error){
    console.log(error)
    res.json({error})
  }
})

async function sendToDiscord(config){
  try{
    console.log('---------axios-start--------')
    const response = await Axios(config);
    console.log('---------axios-end----------')
    console.log(response.data)
    if(response.data == ''){
      return true
    }else{
      return false
    }
  }catch(e){
    return false
  }
}
function generateRandomNumber(n) {
  let result = '';
  for (let i = 0; i < n; i++) {
    result += Math.floor(Math.random() * 10);
  }
  return result;
}
function datetime() {
    const date = new Date(); // 创建一个新的 Date 对象并传入时间戳
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1); // JavaScript 中月份从 0 开始计数，所以需要加 1
    const day = padZero(date.getDate());
    const hour = padZero(date.getHours());
    const minute = padZero(date.getMinutes());
    const second = padZero(date.getSeconds());
  
    // 拼接成 MySQL DATETIME 格式的字符串并返回
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
function padZero(num) {
    return num.toString().padStart(2, '0');
}
function sendConfigFirst(prompt){
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
        authorization: process.env.DC_API_AUTH,
    },
    data:{
        "type": 2,
        "application_id": "936929561302675456",
        "guild_id": "1077497600221126746",
        "channel_id": "1077497600221126749",
        "session_id": process.env.DC_API_SID,
        "data": {
            "version": "1077969938624553050",
            "id": "938956540159881230",
            "name": "imagine",
            "type": 1,
            "options": [{
                "type": 3,
                "name": "prompt",
                "value": prompt,
            }],
            "application_command": {
                "id": "938956540159881230",
                "application_id": "936929561302675456",
                "version": "1077969938624553050",
                "default_permission": true,
                "default_member_permissions": null,
                "type": 1,
                "nsfw": false,
                "name": "imagine",
                "description": "Create images with Midjourney",
                "dm_permission": true,
                "options": [{
                    "type": 3,
                    "name": "prompt",
                    "description": "The prompt to imagine",
                    "required": true
                }]
            },
            "attachments": []
      },
      "nonce": generateRandomNumber(20),
    },
  };
  return config;
}

function sendConfigDetail(message_id, num, message_name){
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
        authorization: process.env.DC_API_AUTH,
    },
    data:{
        "type": 3,
        "nonce": generateRandomNumber(20),
        "guild_id": "1077497600221126746",
        "channel_id": "1077497600221126749",
        "message_flags": 0,
        "message_id": message_id,
        "application_id": "936929561302675456",
        "session_id": process.env.DC_API_SID,
        "data": {
          "component_type": 2,
          "custom_id": "MJ::JOB::upsample::"+ num +"::"+ message_name
        }
    }
  }
  return config
}

function sendConfigNew(message_id, num, message_name){
  let config = {
    method: 'post',
    url: process.env.DC_API_URL,
    headers: {
        authorization: process.env.DC_API_AUTH,
    },
    data:{
        "type": 3,
        "nonce": generateRandomNumber(20),
        "guild_id": "1077497600221126746",
        "channel_id": "1077497600221126749",
        "message_flags": 0,
        "message_id": message_id,
        "application_id": "936929561302675456",
        "session_id": process.env.DC_API_SID,
        "data": {
          "component_type": 2,
          "custom_id": "MJ::JOB::variation::"+ num +"::"+ message_name
        }
    }
  }
  return config
}

module.exports = router;